/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package issr.boundary.vaadin;

import com.vaadin.Application;
import com.vaadin.service.ApplicationContext.TransactionListener;
import com.vaadin.ui.Window;

/**
 *
 * @author Soulreaver
 */
public class MainApplication extends Application implements TransactionListener {

    protected static ThreadLocal<MainApplication> thisApplication = new ThreadLocal<MainApplication>();
    public Handler vh;

    /*
     *  Set ThreadLocal application.
     *  @param ExampleApplication t	
     */
    public static void setProject(MainApplication t) {
        thisApplication.set(t);
    }

    /*
     *  Get ThreadLocal application.
     */
    public static MainApplication getProject() {
        return thisApplication.get();
    }
    /**
     * 
     */
    private static final long serialVersionUID = 740910956394283672L;

    @Override
    public void init() {

        // sets the current application to ThreadLocal.
        setProject(this);

        // Creates the Main Window and then hands over all UI work to the
        // Handler
        setMainWindow(new Window("Gestione di punti vendita e prodotti WebAppplication"));


        vh = new Handler(getMainWindow());

        // Adds a TransactionListener for this class.
        getContext().addTransactionListener(this);

        // Register user change listener for Handler.
        addListener(vh);
    }

    /*
     * Helper to return the Handler attached to a unique application.
     */
    public Handler getHandler() {
        return thisApplication.get().vh;
    }

    /*
     * For ThreadLocal pattern.
     */
    public void transactionStart(Application application, Object transactionData) {
        // Same WebApplicationContext (session) may contain multiple different
        // Toolkit applications, here we are only interested of
        // TrainingApplication related transaction events.
        if (application == MainApplication.this) {
            thisApplication.set(this);
        }
    }

    /**
     * For ThreadLocal pattern, remove application reference
     */
    public void transactionEnd(Application application, Object transactionData) {
        if (application == MainApplication.this) {
            thisApplication.set(null);
        }
    }
}
